/*
 *  Copyright (C), 2015-2024
 *  FileName: keyboard_tool
 *  Author: Tonight丶相拥
 *  Date: 5/16/24
 *  Description: 
 **/

part of 'flutter_tool.dart';

class _KeyboardObserveTool with WidgetsBindingObserver, _CustomNotification {

  _KeyboardObserveTool._() {
    WidgetsBinding.instance.addObserver(this);
  }

  static const String keyboardChangeKey = 'keyboard_height_change\$KeyboardTool';

  double _keyboardHeight = 0;
  bool _isKeyboardShow = false;
  bool get isKeyboardShow => _isKeyboardShow;

  FlutterView get _view => PlatformDispatcher.instance.views.last;

  FlutterView? _getViewById(int id ) {
    return PlatformDispatcher.instance.view(id: id);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // final bottom = MediaQueryData.fromWindow(window).viewInsets.bottom;
    final bottom = MediaQueryData.fromView(_view).viewInsets.bottom;
    // 键盘存在中间态，回调是键盘冒出来的高度
    _keyboardHeight = math.max(_keyboardHeight, bottom);

    if (bottom == 0) {
      _isKeyboardShow = false;
    } else {
      _isKeyboardShow = true;
    }
    /*
    if (bottom == 0) {
      _isKeyboardShow = false;
    } else if (bottom == _keyboardHeight || _keyboardHeight == 0) {
      _isKeyboardShow = true;
    } else {
      _isKeyboardShow = null;
    }*/

    notificationListener(name: _KeyboardObserveTool.keyboardChangeKey, parameter: bottom);

    // 键盘完全收起或展开再刷新页面
    // if (_isKeyboardShow/* && _preKeyboardShow != _isKeyboardShow */) {
    //   // _keyboardStateNotifier.notifyListeners();
    // }

    if (bottom < _keyboardHeight) {
      // todo: 设置 _keyboard 高度
      // _sp?.setDouble(KEYBOARD_MAX_HEIGHT, _keyboardHeight);
    }
  }
}

/*class TestClass with KeyboardMixin implements KeyboardChange {

  @override
  void onKeyboardChange(param) {
    // TODO: implement onKeyboardChange

  }
}*/